package cn.bcsp.controller;

import cn.bcsp.exception.LoginException;
import cn.bcsp.pojo.LoginUser;
import cn.bcsp.pojo.SysRole;
import cn.bcsp.pojo.SysUser;
import cn.bcsp.service.RoleService;
import cn.bcsp.service.SysUserService;
import cn.bcsp.util.PageUtil;
import com.alibaba.fastjson.JSON;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.mapper.MapperFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.File;
import java.util.*;


/**
 * @Description: TODO
 * @author: wangyue
 * @date: 2021年07月14日 15:32
 */
@Controller
@RequestMapping("/system")
public class SysUserController {

    @Resource(name = "sysUserService")
    private SysUserService sysUserService;

    @Resource(name = "roleService")
    private RoleService roleService;


    @RequestMapping("/user/toAdd")
    public String toAddUser() {
//        List<SysRole> sysRoleList = roleService.queryAll();
//        model.addAttribute("roleList", sysRoleList);
        return "sysUser/add";
    }

    @RequestMapping("/user/toUpPwd")
    public String toUpPwd() {

        return "sysUser/updatePassword";
    }

    @ResponseBody
    @RequestMapping("/putterPwd")
    public boolean lookOldPwd(@RequestParam("oldPwd") String oldPwd, HttpSession session) {

        SysUser user = (SysUser) session.getAttribute("user");
        boolean answer = user.getPassword().equals(oldPwd);

        return answer;
    }


    @ResponseBody
    @RequestMapping("/updatePwd")
    public Integer updatePwd(@RequestParam("newPwd") String newPwd, HttpSession session) {
        SysUser user = (SysUser) session.getAttribute("user");
        SysUser sysUser = new SysUser();
        sysUser.setPassword(newPwd);
        sysUser.setId(user.getId());
        int sysUser1 = sysUserService.editSysUser(sysUser);

        return sysUser1;
    }

    @RequestMapping("/user/view/{id}")
    public String viewUser(@PathVariable(name = "id") int id, Model model) {
        SysUser sysUser = sysUserService.querySysUser(id);
        model.addAttribute("sysUser", sysUser);
        return "sysUser/view";
    }

    @RequestMapping("/user/doAdd")
    public String doAddUser(@RequestParam("idPic") MultipartFile[] idPic, SysUser sysUser, HttpSession session, Model model) throws Exception {
        //获得参数信息
        System.out.println("0");

        for (int i = 0; i < idPic.length; i++) {

            MultipartFile multipartFile = idPic[i];
            if (!multipartFile.isEmpty()) {
                String uploadPath = session.getServletContext().getRealPath("statics" + File.separator + "upload");

                System.out.println("1");

                String builderPath = multipartFile.getOriginalFilename();
                String uuPath = UUID.randomUUID().toString();

                String newPath = uuPath + builderPath;

                File myFile = new File(uploadPath, newPath);
                System.out.println("2");
                multipartFile.transferTo(myFile);

                String path = "statics" + File.separator + "upload" + File.separator + newPath;
                if (i == 0) {
                    sysUser.setIdPics(path);
                } else if (i == 1) {
                    sysUser.setIdPics1(path);
                } else {
                    sysUser.setIdPics2(path);
                }


            }

        }


        sysUser.setCreatedTime(new Date()); //新增用户的时间
        SysUser loginUser = (SysUser) session.getAttribute("user");
        if (loginUser == null) { //如果用户没有登录
            return "forward:/system/toLogin";
        }
        sysUser.setCreatedUserId(loginUser.getId());   //新增用户的用户ID
        //保存参数
        int result = sysUserService.addSysUser(sysUser);
        if (result > 0) {
            model.addAttribute("msg", "新增成功");
        } else {
            model.addAttribute("msg", "新增失败");
        }
        return "forward:/system/users";  //跳转到用户列表
    }


    @RequestMapping("/logout")
    public String logout(HttpSession session) {
        session.invalidate();
        return "forward:/system/toLogin";
    }


    @RequestMapping("/users")
    public String users(@RequestParam(name = "realName", defaultValue = "") String realName,
                        @RequestParam(name = "roleId", defaultValue = "0") int roleId,
                        @RequestParam(name = "currentPage", defaultValue = "1") int currentPage,
                        Model model) {
        //查询角色信息
        List<SysRole> lists = roleService.queryAll();
        //分页查用户信息
        PageUtil<SysUser> pageUtil =
                sysUserService.querySysUserByPage(realName, roleId, currentPage);

        model.addAttribute("pageUtil", pageUtil);
        //角色信息保存到作用域中
        model.addAttribute("rolesList", lists);
        //保存查询条件
        model.addAttribute("realName", realName);
        model.addAttribute("roleId", roleId);
        return "sysUser/list";
    }


    /**
     * 处理SysUserController类上的异常信息(Exception.class)
     *
     * @return
     * @author Administrator
     * @describe:
     * @date 2021-07-14 16:49
     */
//    @ExceptionHandler(Exception.class)
//    public String exceptionHandler(Exception exception, Model model){
//        model.addAttribute("exception",exception); //将异常信息保存到request作用域中
//        return "sysError";
//    }
    @RequestMapping("/doLogin")
    public String doLogin(@Valid LoginUser loginUser, BindingResult bindingResult,
                          HttpSession session, HttpServletRequest request) throws Exception {

        boolean hasErrors = bindingResult.hasErrors();
        if (hasErrors) {
            return "login";
        }

        SysUser sysUser =
                sysUserService.login(loginUser.getAccount(), loginUser.getPassword());

        if (sysUser == null) {
            throw new LoginException("帐号或者密码错误");
        } else {
            session.setAttribute("user", sysUser);
            return "forward:/system/users";
        }
    }


    @RequestMapping("/toLogin")
    public String toLogin(Model model) {
        LoginUser loginUser = new LoginUser();

        model.addAttribute("loginUser", loginUser);
        return "login";
    }


    @RequestMapping("/user/toUpdate/{uid}")
    public String toUpdate(@PathVariable("uid") Integer id, Model model) {

        SysUser sysUser = sysUserService.querySysUser(id);
        List<SysRole> sysRoles = roleService.queryAll();
        model.addAttribute("sysUser", sysUser);
        model.addAttribute("roleList", sysRoles);

        return "sysUser/update";
    }


    @RequestMapping("user/update")
    public String doUpdate(SysUser sysUser, Model model) {
        int res = sysUserService.editSysUser(sysUser);

        String answer = "失败";
        if (res == 1) {
            answer = "成功";
        }
        model.addAttribute("msg", answer);
        return "forward:/system/users";
    }


    @RequestMapping("/del/{id}")
    @ResponseBody
    public Map<String, Object> toDel(@PathVariable("id") Integer id, HttpSession session) {
        Map<String, Object> map = new HashMap<>();
        SysUser user = (SysUser) session.getAttribute("user");
        if (id.equals(user.getId())) {
            map.put("res", "choose");
        }

        if (id.equals(user)) {
            map.put("res", "error");
        } else {
            int res = sysUserService.delById(id);
            map.put("res", "ok");
        }


        return map;
    }


    @ResponseBody
    @GetMapping("/isExists")
    public Map<String, Object> isExists(@RequestParam("account") String param1) {

        int account = sysUserService.findAccount(param1);
        int sysUser = sysUserService.addSysUser(null);
        int edit = sysUserService.editSysUser(null);


        Map<String, Object> map = new HashMap<>();
        map.put("account", account);

        return map;
    }


    @ResponseBody
    @GetMapping(value = "/myView/{id}")
    public Object myView(@PathVariable("id") Integer id) {

        SysUser sysUser = sysUserService.querySysUser(id);


        return sysUser;
    }


}
